package com.glowdayz.glowmee;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.PorterDuff;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.glowdayz.common.ActivityManager;
import com.glowdayz.common.CDialog;
import com.glowdayz.common.DateTime;
import com.glowdayz.common.ImageDownloader;
import com.glowdayz.common.XmlParser;
import com.glowdayz.model.AdminTableCMD;

public class Notice extends Activity implements OnClickListener {
	
	private ActivityManager am = ActivityManager.getInstance();
	
	ExpandableListView noticeList = null;
	ExpandableListAdapter listAdapter = null;
	List<AdminTableCMD> listDataHeader;
	HashMap<AdminTableCMD, List<AdminTableCMD>> listDataChild;
	String header = null;
	
	LinearLayout llFooter = null;
	Button btPage = null;
	
	boolean isFirst = true;
	
	/********** 페이지 구현 **********/
	private int page = 1;						// 현재 페이지
	private final static int pageSize = 50;		// 한 페이지에 보일 수
	private int totalCount = 0;					// 전체 게시물 수
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_notice);
		
		am.addActivity(this);
		
		ImageView okBt = (ImageView) findViewById(R.id.okBt);
		okBt.setVisibility(View.GONE);
		
		ImageView backBt = (ImageView) findViewById(R.id.backBt);
		backBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		backBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		TextView textTitle = (TextView) findViewById(R.id.textTitle);
		textTitle.setText("공지사항");
		
		noticeList = (ExpandableListView) findViewById(R.id.noticeList);
		
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		llFooter = (LinearLayout) inflater.inflate(R.layout.list_footer2, null);
		llFooter.setVisibility(View.GONE);
		noticeList.addFooterView(llFooter);
		btPage = (Button) llFooter.findViewById(R.id.btPage);
		btPage.setOnClickListener(this);
		
		listDataHeader = new ArrayList<AdminTableCMD>();
		listDataChild = new HashMap<AdminTableCMD, List<AdminTableCMD>>();
		
		(new NoticeWorker()).execute();
		
		noticeList.setDividerHeight(2);
		noticeList.setGroupIndicator(null);
		noticeList.setClickable(true);
		
		// Listview Group click listener
		noticeList.setOnGroupClickListener(new OnGroupClickListener() {
			@Override
			public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
				 //Toast.makeText(getApplicationContext(), "Group Clicked " + listDataHeader.get(groupPosition), Toast.LENGTH_SHORT).show();
				return false;
			} 
		});
		// Listview Group expanded listener
		noticeList.setOnGroupExpandListener(new OnGroupExpandListener() {
			@Override
			public void onGroupExpand(int groupPosition) {
				//Toast.makeText(getApplicationContext(),listDataHeader.get(groupPosition) + " Expanded", Toast.LENGTH_SHORT).show();
			}
		});
		// Listview Group collasped listener
		noticeList.setOnGroupCollapseListener(new OnGroupCollapseListener() {
		@Override
			public void onGroupCollapse(int groupPosition) {
				//Toast.makeText(getApplicationContext(), listDataHeader.get(groupPosition) + " Collapsed", Toast.LENGTH_SHORT).show();

			}
		});
		// Listview on child click listener
		noticeList.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
				// header=listDataHeader.get(groupPosition);
				// Toast.makeText(getApplicationContext(), listDataHeader.get(groupPosition) + " : " + listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition),Toast.LENGTH_SHORT).show();
				return false;
			}	
			
		});
	}

	public class ExpandableListAdapter extends BaseExpandableListAdapter {

		private Context context;
		private List<AdminTableCMD> listDataHeader; // header titles
		// child data in format of header title, child title
		private HashMap<AdminTableCMD, List<AdminTableCMD>> listDataChild;
		public ExpandableListAdapter(Context context, List<AdminTableCMD> listDataHeader, HashMap<AdminTableCMD, List<AdminTableCMD>> listChildData) {
			this.context = context;
			this.listDataHeader = listDataHeader;
			this.listDataChild = listChildData;
		}
		@Override
		public Object getChild(int groupPosition, int childPosititon) {
			return this.listDataChild.get(this.listDataHeader.get(groupPosition)).get(childPosititon);
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
			AdminTableCMD cmd = (AdminTableCMD) getChild(groupPosition, childPosition);
			if (convertView == null) {
				LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = infalInflater.inflate(R.layout.list_notice_item, null);
			}
			TextView txtListChild = (TextView) convertView.findViewById(R.id.boardText);
			ImageView noticeTextImg = (ImageView) convertView.findViewById(R.id.noticeTextImg);
			txtListChild.setText(cmd.getBoardText());
			if (!cmd.getModified_date().equals("null")) {
				noticeTextImg.setVisibility(View.VISIBLE);
				ImageDownloader.getInstance().download(getResources().getString(R.string.server_url) + cmd.getModified_date().trim(), noticeTextImg);
			} else {
				noticeTextImg.setVisibility(View.GONE);
			}
			return convertView;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return this.listDataChild.get(this.listDataHeader.get(groupPosition)).size();
		}

		@Override
		public Object getGroup(int groupPosition) {
			return this.listDataHeader.get(groupPosition);
		}

		@Override
		public int getGroupCount() {
			return this.listDataHeader.size();
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
			AdminTableCMD cmd = (AdminTableCMD) getGroup(groupPosition);
			if (convertView == null) {
				LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = infalInflater.inflate(R.layout.list_notice_group, null);
			}
			TextView noticeTitle = (TextView) convertView.findViewById(R.id.noticeTitle);
			TextView noticeDate = (TextView) convertView.findViewById(R.id.noticeDate);
			
			noticeTitle.setText(cmd.getBoardTitle());
			noticeDate.setText(DateTime.getInstance().getDateTimeString4(cmd.getCreate_date()));
			
			ImageView noticeTitleImg = (ImageView) convertView.findViewById(R.id.noticeTitleImg);
			//LinearLayout noticeLayout = (LinearLayout) convertView.findViewById(R.id.noticeLayout);
			
			if(isExpanded){
				noticeTitleImg.setImageResource(R.drawable.button_allow_under);
				//noticeLayout.setBackgroundColor(Color.parseColor("#f5f5f5"));
			} else {
				noticeTitleImg.setImageResource(R.drawable.button_allow);
				//noticeLayout.setBackgroundColor(Color.parseColor("#ffffff"));
			}
			
			return convertView;
		}

		@Override
		public boolean hasStableIds() {
			return false;
		}
		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return false;
		}
    }
	
	public class NoticeWorker extends AsyncTask<Object, AdminTableCMD, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(Notice.this);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			String url = getResources().getString(R.string.server_url) + "/glowmee/noticeXml.do?page=" + page + "&count=" + pageSize;
			
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idAdminBoard = 0;
				String boardTitle = null;
				String boardText = null;
				String create_date = null;
				String thumbnail = null;
				
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("totalArticleCount")) {
							parser.next();
							totalCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idAdminBoard")) {
							parser.next();
							idAdminBoard = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("boardTitle")) {
							parser.next();
							boardTitle = parser.getText();
						} else if (tag.equals("boardText")) {
							parser.next();
							boardText = parser.getText();
						} else if (tag.equals("create_date")) {
							parser.next();
							create_date = parser.getText();
						} else if (tag.equals("thumbnail")) {
							parser.next();
							thumbnail = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("item")) {
							AdminTableCMD item = new AdminTableCMD(idAdminBoard, boardTitle, boardText, thumbnail, create_date);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(AdminTableCMD... param) {
			listDataHeader.add(param[0]);
			List<AdminTableCMD> list = new ArrayList<AdminTableCMD>();
			list.add(param[0]);
			listDataChild.put(param[0], list);
		}

		@Override
		protected void onPostExecute(Object param) {
			/** 모든 처리 종료 후, 페이지 구현 */
			// 전체 페이지 수
			int pageCount = ((totalCount - 1) / pageSize) + 1;
			
			if (pageCount > 0 && page < pageCount) {
				// 화면 표시
				llFooter.setVisibility(View.VISIBLE);
			} else {
				// 화면 숨김
				llFooter.setVisibility(View.GONE);
			}
			
			if (isFirst) {
				listAdapter = new ExpandableListAdapter(Notice.this, listDataHeader, listDataChild);
				noticeList.setAdapter(listAdapter);
				isFirst = false;
			}
			
			CDialog.hideLoading();
		}
		
		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(Notice.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new NoticeWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btPage:
			// 다음페이지 버튼
			page++;
			(new NoticeWorker()).execute();
			break;
		}
	}
	
    @Override
	protected void onDestroy() {
		super.onDestroy();
		am.removeActivity(this);
	}
	
}
